#pragma once


#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <unordered_map>
#include "Common.hpp"
#include "Log.hpp"

using namespace LogModule;


const std::string Sep = "\r\n";
const std::string LineSep = " ";
const std::string HeaderLineSep = ": ";
const std::string BlankLine = Sep;
const std::string defaulthomepage = "wwwroot";
const std::string http_version = "HTTP/1.0";
const std::string page404 = "wwwroot/404.html";
const std::string firstpage = "index.html";

class HttpRequest
{
public:
    HttpRequest()
    {}
    ~HttpRequest()
    {}
    bool ParseHeaderkv()
    {
        std::string key,value;
        for(auto& header : _req_header)
        {
            //Connection: keep-alive
            if(SplitString(header,HeaderLineSep,&key,&value))
            {
                _header_kv.insert(std::make_pair(key,value));
            }
        }
        return true;
    }
    bool ParseHeader(std::string& request_str)
    {
        std::string line;
        while(true)
        {
            bool r = ParseOneLine(request_str,&line,Sep);
            if(r && !line.empty())
            {
                _req_header.push_back(line);
            }
            else if(r && line.empty())
            {
                _blank_line = Sep;
                break;
            }
            else
            {
                return false;
            }
        }
        ParseHeaderkv();
        return true;
    }
    void Deserialize(std::string& request_str)
    {
        if(ParseOneLine(request_str,&_req_line,Sep))
        {
            //提取请求行内的详细字段
            ParseReqLine(_req_line,LineSep);
            ParseHeader(request_str);
            _body = request_str;

            //分析请求中是否有参数
            if(_method == "POST")
            {
                _isexec = true;
                _args = _body;
                _path = _uri;
                LOG(LogLevel::DEBUG) << "POST: _path: " << _path;
                LOG(LogLevel::DEBUG) << "POST: _args: " << _args;
            }
            else if(_method == "GET")
            {
                auto pos = _uri.find("?");
                if(pos != std::string::npos)
                {
                    // /login?name=zhangsan&passwd=12345
                    _isexec = true;
                    _path = _uri.substr(0,pos);
                    _args = _uri.substr(pos + 1);
                    LOG(LogLevel::DEBUG) << "_path: " << _path;
                    LOG(LogLevel::DEBUG) << "_args: " << _args;
                }
            }
        }
    }
    void Print()
    {
        std::cout << "_method: " << _method << std::endl;
        std::cout << "_uri: " << _uri << std::endl;
        std::cout << "_version: " << _version << std::endl;

        for(auto& kv : _header_kv)
        {
            std::cout << kv.first << " # " << kv.second << std::endl;
        }
        std::cout << "_blank_line: " << _blank_line << std::endl;
        std::cout << "body: " << _body << std::endl;
    }
    std::string GetContent(std::string path)
    {
        // std::string content;
        // std::ifstream in(_uri);
        // if(!in.is_open())
        // {
        //     return std::string();
        // }
        // std::string line;
        // while(std::getline(in,line))
        // {
        //     content += line;
        // }
        // in.close();
        // return content;

        std::string content;
        std::ifstream in(path,std::ios::binary);
        if(!in.is_open())
        {
            return std::string();
        }
        in.seekg(0,in.end);
        int filesize = in.tellg();
        in.seekg(0,in.beg);
        content.resize(filesize);
        in.read((char*)content.c_str(),filesize);
        in.close(); 
        return content;
    }
    std::string Uri()
    {
        return _uri;
    }
    void SetUri(const std::string newuri)
    {
        _uri = newuri;
    }
    std::string Path()
    {
        return _path;
    }
    std::string Args()
    {
        return _args;
    }
    std::string Suffix()
    {
        auto pos = _uri.rfind(".");
        if(pos == std::string::npos)
        {
            return std::string(".html");
        }
        return _uri.substr(pos);
    }
    bool IsHasArgs()
    {
        return _isexec;
    }
private:
    void ParseReqLine(std::string& _req_line,const std::string sep)
    {
        std::stringstream ss(_req_line);
        ss >> _method >> _uri >> _version;
    }
private:
    std::string _req_line;
    std::vector<std::string> _req_header;
    std::string _blank_line;
    std::string _body;
    //反序列化的过程中,细化我们解析的字段
    std::string _method;
    std::string _uri;
    std::string _path;
    std::string _args;
    std::string _version;
    std::unordered_map<std::string,std::string> _header_kv; 
    bool _isexec = false;
};




//对于http来说,任何请求都要有对应的应答
class HttpResponse
{
public:
    HttpResponse():_version(http_version),_blank_line(Sep)
    {

    }
    ~HttpResponse()
    {

    }
    void Build(HttpRequest& req)
    {
// #define TestRedir 1
#ifdef TestRedir
        std::string uri = req.Uri();
        if(uri.back() == '/')
        {
            _status_code = 302;
            _status_desc = CodeToDesc(_status_code);
            // SetHeader("Location","https://www.qq.com/");
            SetHeader("Location","http://8.137.24.157:8080/register.html");
            return;
        }
#else
        std::string uri = defaulthomepage + req.Uri();
        // wwwroot/     ->  wwwroot/index.html
        // wwwroot/a/b  ->  wwwroot/a/b/index.html
        if(uri.back() == '/')
        {
            uri += firstpage;
            req.SetUri(uri);
        }

        LOG(LogLevel::DEBUG) << "------客户端在请求: " << req.Uri();
        req.Print();
        LOG(LogLevel::DEBUG) << "---------------------\n";

        _content = req.GetContent(uri);
        if(_content.empty())
        {
            //当前用户请求资源不存在
            _status_code = 404;
            req.SetUri(page404);
            _content = req.GetContent(page404);
        }
        else
        {
            _status_code = 200;
        }

        _status_desc = CodeToDesc(_status_code);
        if(!_content.empty())
        {
            SetHeader("Content-Length",std::to_string(_content.size()));
        }
        std::string mime_type = SuffixToDesc(req.Suffix());
        SetHeader("Content-Type",mime_type);
        _body = _content;
#endif
    }
    void Serialize(std::string* resp_str)
    {
        for(auto& header : _header_kv)
        {
            _resp_header.push_back(header.first + HeaderLineSep + header.second);
        }
        _resp_line = _version + LineSep + std::to_string(_status_code) + LineSep + _status_desc + Sep;
        //序列化
        *resp_str = _resp_line;
        for(auto& line : _resp_header)
        {
            *resp_str += (line + Sep);
        }
        *resp_str += _blank_line;
        *resp_str += _body;
    }
    void SetHeader(const std::string& k,const std::string& v)
    {
        _header_kv[k] = v;
    }
    void SetCode(int code)
    {
        _status_code = code;
        _status_desc = CodeToDesc(_status_code);
    }
    void SetBody(std::string body)
    {
        _body = body;
    }
private:
    std::string CodeToDesc(int code)
    {
        switch(code)
        {
            case 200:
                return "OK";
            case 404:
                return "Not Found";
            case 301:
                return "Moved Permanently";
            case 302:
                return "Found";
            default:
                return std::string();
        }
    }
    std::string SuffixToDesc(const std::string& suffix)
    {
        if(suffix == ".html")
        {
            return "text/html";
        }
        else if(suffix == ".png")
        {
            return "image/png";
        }
        return "text/html";
    }
private:
    //必备的要素
    std::string _version;
    int _status_code;
    std::string _status_desc;
    std::string _content;
    std::unordered_map<std::string,std::string> _header_kv;

    //最终要这四部分,构建应答
    std::string _resp_line;
    std::vector<std::string> _resp_header;
    std::string _blank_line;
    std::string _body;
};


